import { Button, Form, Input, message, notification, PageHeader, Select, Steps } from 'antd'
import axios from 'axios';
import NewsEditor from '../../../components/NewsEditor'
import React, { useEffect, useRef, useState } from 'react'
import Style from './News.module.css'
const { Option } = Select;

export default function NewsUpdate(props) {

    // 存储步骤条Steps组件当前进行到第几步
    const [current, setCurrent] = useState(0)

    // 新闻标题和新闻分类
    const [formInfo, setFormInfo] = useState({})

    // 新闻主体内容
    const [content, setContent] = useState('')

    // 存储新闻类型数据
    const [categoryList, setCategoryList] = useState([])

    // 存储Form组件的实例
    const NewsForm = useRef(null)

    // 获取新闻的相关信息
    useEffect(() => {
        // 因为当前组件是路由组件，所以可以通过props.match.params.id获取的是当前路由路径中的id值，根据这个id值去后端请求数据
        axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
            const { title, categoryId, content } = res.data
            // 根据NewsForm获取Form组件实例，再利用setFieldsValue方法给Form组件下的对应的表单项设置内容
            NewsForm.current.setFieldsValue({
                title: title,
                categoryId: categoryId,
            })

            setContent(content)
        })
    }, [props.match.params.id])

    // 获取新闻类型数据
    useEffect(() => {
        axios.get('/categories').then((res) => {
            setCategoryList(res.data)
        })
    }, [])

    // 点击下一步按钮
    const handleNext = () => {
        // 表单验证成功则走下一步，失败则不执行
        if (current === 0) {
            // 
            NewsForm.current.validateFields().then(res => {
                setFormInfo(res)
                setCurrent(current + 1)
            }).catch(err => {
                console.log(err);
            })
        } else {
            if (content === "" || content.trim() === "<p></p>") {
                message.error("新闻内容不能为空")
            } else {
                setCurrent(current + 1)
            }
            console.log(formInfo, content);
        }
    }

    // 点击上一步按钮
    const handlePrevious = () => {
        setCurrent(current - 1)
    }

    // 从本地存储解构出来用户数据
    // const User = JSON.parse(localStorage.getItem("token"))

    // 保存到草稿箱
    const handleSave = (auditState) => {
        axios.patch(`/news/${props.match.params.id}`, {
            ...formInfo,
            "content": content,
            "auditState": auditState,
        }).then(res => {
            // 判断auditState===0的话跳转到草稿箱页面，反之auditState===1的话跳转到审核列表页面
            props.history.push(auditState === 0 ? "/news-manage/draft" : "/audit-manage/list")

            notification.info({
                message: "通知",
                description: auditState === 0 ? "你可以到草稿箱中查看" : "你可以在审核列表里面查看",
                // 设置提示框组件的出现位置
                placement: "top"
            });
        })
    }

    return (
        <div>

            {/* 页头 */}
            <PageHeader
                className="site-page-header"
                title="更新新闻"
                subTitle="Update the News"
                onBack={() => props.history.goBack()}
            />

            {/* 步骤条组件 */}
            <Steps
                current={current}
                items={[
                    {
                        title: '基本信息',
                        description: "新闻标题，新闻分类"
                    },
                    {
                        title: '新闻内容',
                        description: "新闻主体内容"
                    },
                    {
                        title: '新闻提交',
                        description: "保存草稿或者提交审核"
                    },
                ]}
            />

            {/* 内容区 */}
            <div className={Style.stepsContent}>

                <div className={current === 0 ? '' : Style.active}>
                    <Form name="control-hooks" ref={NewsForm}>
                        <Form.Item
                            label="新闻标题"
                            name="title"
                            rules={[
                                {
                                    required: true, message: 'Please input your username!'
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item name="categoryId" label="新闻类型" rules={[{ required: true }]}>
                            <Select
                                placeholder="Select a option and change input text above"
                            >
                                {
                                    categoryList.map(item =>
                                        <Option value={item.id} key={item.id}>{item.title}</Option>
                                    )
                                }
                            </Select>
                        </Form.Item>
                    </Form>
                </div>

                <div className={current === 1 ? '' : Style.active}>
                    {/* 富文本编译器 */}
                    {/* 将新闻主体内容content作为参数传递给NewsEditor子组件 */}
                    <NewsEditor content={content} getContent={(value) => {
                        setContent(value)
                    }}></NewsEditor>
                </div>

                <div className={current === 2 ? '' : Style.active}>
                    <input />
                </div>
            </div>


            {/* 按钮区 */}
            <div style={{ marginTop: "20px" }}>
                {
                    current === 2 && <span>
                        <Button type="primary" onClick={() => {
                            handleSave(0)
                        }}>保存到草稿箱</Button>

                        <Button danger style={{ marginLeft: "10px" }} onClick={() => {
                            handleSave(1)
                        }}>提交审核</Button>
                    </span>
                }
                {
                    current < 2 && <Button  type="primary" onClick={() => {
                        handleNext()
                    }}>下一步</Button>
                }
                {
                    current > 0 && <Button  style={{ marginLeft: "10px" }} onClick={() => {
                        handlePrevious()
                    }}>上一步</Button>
                }
            </div>
        </div>
    )
}
